package com.bw.lib_common.websocket

import android.os.Handler
import android.os.Looper
import android.util.Log

import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
/**
 * @author ykj
 * @date 2025-10-29 21:03
 * @description
 */
class WebSocketUtils {
    private var webSocketClient: WebSocketClient? = null
    private var receiveMessageListener: ReceiveMessageListener? = null
    private var uri: String? = null


    constructor(builder: Builder){
        if (builder.uri.isNullOrEmpty()){
            throw NullPointerException("uri is null")
        }
        this.receiveMessageListener = builder.receiveMessageListener
        this.uri = builder.uri
        initWS()
    }

    /**
     * 初始化websocket
     */
    fun initWS(){
        handler.postDelayed(runnable, HEART_BEAT_TIME.toLong()) //启动心跳
        if (webSocketClient == null){
            initWebSocket() //创建websocket
        }else if (webSocketClient?.isClosed == true){
            reconnectWs() //重连websocket
        }
    }

    fun initWebSocket(){
        webSocketClient = object :WebSocketClient(URI(uri)){
            override fun onOpen(p0: ServerHandshake?) {
                //打开链接
                if (receiveMessageListener != null){
                    receiveMessageListener?.onOpen(p0)
                }
            }

            override fun onMessage(p0: String?) {
                //接受到消息
                if (receiveMessageListener != null){
                    receiveMessageListener?.onMessage(p0)
                }
            }

            override fun onClose(p0: Int, p1: String?, p2: Boolean) {
                //关闭链接
                if (p0 != 1000){ //1000是正常关闭close方法
                    reconnect()
                }
                if (receiveMessageListener != null){
                    receiveMessageListener?.onClose(p0,p1,p2)
                }
            }

            override fun onError(p0: java.lang.Exception?) {
                //出错
                if (receiveMessageListener != null){
                    receiveMessageListener?.onError(p0)
                }
            }

        }
        webSocketClient?.connectionLostTimeout = 30 * 1000 //设置超时时间
        webSocketClient?.connect()
    }

    /**
     * 重连
     */
    fun reconnectWs(){
        webSocketClient?.reconnect()
    }

    /**
     * 断开链接
     */
    fun closeConnect(){
        handler.removeCallbacksAndMessages(null) //移除心跳
        if (webSocketClient != null){
            webSocketClient?.close()
            webSocketClient = null
        }
    }
    /**
     * 发送消息
     */
    fun sendMsg(msg:String){
        if (webSocketClient != null){
            if (webSocketClient?.isOpen == true){
                Log.d(TAG, "发送消息:$msg ")
                webSocketClient?.send(msg)
            }
        }
    }

    /**
     * 心跳保活机制
     */
    companion object{
        private const val TAG = "WebSocketUtils"
        private const val HEART_BEAT_TIME = 10 * 1000 //心跳时间
    }
    private val handler: Handler = Handler(Looper.getMainLooper())
    private val runnable = object : Runnable { //心跳任务
        override fun run() {
            if (webSocketClient != null){
                if (webSocketClient?.isOpen == true){
                    Log.d(TAG, "发送心跳包，链接状态为open")
                    sendMsg("{\"type\":\"heartbeat\"}")
                }else{
                    Log.d(TAG, "发送心跳包，链接状态为close")
                    reconnectWs()
                }
            }else{
                Log.d(TAG, "发送心跳包，client为null，创建client")
                initWebSocket()
            }
            handler.postDelayed(this, HEART_BEAT_TIME.toLong())
        }
    }









    /**
     * 构建者模式
     */
    class Builder {
        var uri:String = ""
        var receiveMessageListener: ReceiveMessageListener? = null
        fun setUri(uri: String): Builder {
            this.uri = uri
            return this
        }

        fun setReceiveMessageListener(receiveMessageListener: ReceiveMessageListener): Builder {
            this.receiveMessageListener = receiveMessageListener
            return this
        }

        fun build(): WebSocketUtils {
            return WebSocketUtils(this)
        }
    }

    /**
     * 消息回调监听
     */
    interface ReceiveMessageListener {
        fun onMessage(message: String?)
        fun onOpen(shake: ServerHandshake?)
        fun onClose(code: Int, reason: String?, remote: Boolean)
        fun onError(ex: Exception?)
    }
}